<template>
  <el-card>
    <div class="head-container">
      <el-input
        v-model="searchText"
        placeholder="请输入"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
    </div>
    <div>
      <el-radio-group v-model="seltype" size="small">
        <el-radio-button label="river">水源地类型</el-radio-button>
        <el-radio-button label="region">行政区划</el-radio-button>
      </el-radio-group>
    </div>
    <div class="head-container">
      <el-tree
        :data="deptOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        default-expand-all
        ref="tree"
        node-key="id"
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>
  </el-card>
</template>

<script>
import {
  getRiverSegmentTree,
  getRiverTree,
  getDistrictTree,
} from "@/api/commonApi";
export default {
  name: "TreeSelect",
  data() {
    return {
      searchText: "",
      seltype: "river",
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeDataLoaded: false, // 标记树形数据是否加载完成
    };
  },
  watch: {
    searchText(val) {
      this.$refs.tree.filter(val);
    },
    seltype: {
      handler(newVal) {
        if (newVal === "river") {
          this.getSydTree();
        } else if (newVal === "region") {
          this.getRiverRegin();
        }
      },
      immediate: true, // 初始化时也会执行
    },
  },
  methods: {
    // 节点过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 将扁平数据转换为树形结构
    convertToTree(data) {
      // 创建id到节点的映射表
      const nodeMap = {};

      // 初始化所有节点，保留原有id，添加label和children
      data.forEach((node) => {
        nodeMap[node.id] = {
          ...node, // 保留所有原始字段（包括id）
          label: node.name, // 添加label字段，值为name
          children: [], // 初始化子节点数组
        };
      });

      // 构建树形结构
      const tree = [];
      data.forEach((node) => {
        const currentNode = nodeMap[node.id];
        // 处理pId为null/undefined的情况，统一视为根节点
        const parentId =
          node.pId === null || node.pId === undefined ? "0" : node.pId;
        const parentNode = nodeMap[parentId];

        if (parentNode) {
          // 存在父节点，添加到父节点的children中
          parentNode.children.push(currentNode);
        } else {
          // 根节点直接加入树
          tree.push(currentNode);
        }
      });

      return tree;
    },
    // 获取水源地
    getSydTree() {
      let query = {
        segmentType: "IsAuto",
        segmentTypeDrink: "show",
      };
      getRiverSegmentTree(query).then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
          this.treeDataLoaded = true;
          // 确保DOM更新后执行选中操作
          this.$nextTick(() => this.setDefaultCheckedNode());
        }
      });
    },
    // 获取行政区划树
    getRiverRegin() {
      let query = {
        segmentTypeDrink: "show",
        segmentType: "IsAuto",
      };
      getDistrictTree(query).then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
          this.treeDataLoaded = true;
          // 确保DOM更新后执行选中操作
          this.$nextTick(() => this.setDefaultCheckedNode());
        }
      });
    },
    // 设置默认选中的节点
    setDefaultCheckedNode() {
      const tree = this.$refs.tree;
      if (!tree || !this.deptOptions.length) return;

      // 获取第一个根节点
      const firstRootNode = this.deptOptions[0];
      if (!firstRootNode || !firstRootNode.children.length) return;

      // 获取第一个根节点下的最后一个子节点
      const children = firstRootNode.children;
      const targetNode = children[children.length - 1];
      if (!targetNode) return;

      // 设置选中状态
      tree.setCurrentKey(targetNode.id);
      // 触发点击事件
      this.handleNodeClick(targetNode);
    },
    // 点击节点时触发
    handleNodeClick(data, node) {
      console.log("点击的节点数据：", data);
      if (data.children.length > 0) {
        return;
      }
      let ids = data.id;
      this.$emit("treeNodeClickk", ids);
    },
  },
};
</script>

<style></style>
